import './sdk-wechat.3.23.5.js';

App({
  globalData: {
    userInfo: null,
    userToken: null,
    userId: null,  // 添加 userId 存储
    tokenExpireTime: null,  // 添加 tokenExpireTime 存储
  },
  
  onLaunch: function () {
    wx.BaaS.init('ab9f4c1a9bb883d6fa47');
    wx.BaaS.auth.loginWithWechat(); // 静默登录

    // 检查缓存中的 Token 和 userId
    let userToken = wx.getStorageSync('userToken');
    let userId = wx.getStorageSync('userId');
    let tokenExpireTime = wx.getStorageSync('tokenExpireTime');

    if (!userToken || !userId||!tokenExpireTime) {
      this.userLogin();  // 如果缓存中没有 Token 或 userId，进行登录
    } else {
      // 检查 session 是否过期
      wx.checkSession({
        success: () => {
          console.log('Session is valid');
          this.globalData.userToken = userToken;
          this.globalData.userId = userId;
          this.globalData.tokenExpireTime = tokenExpireTime;
          this.checkTokenValidity();
        },
        fail: () => {
          console.log('Session expired, re-login');
          this.userLogin();
        }
      });
    }
  },
  
  userLogin() {
    wx.showLoading({
      title: '正在登录...',
    });
    wx.login({
      success: res => {
        wx.request({
          url: 'http://localhost:3000/login?code=' + res.code,
          method: 'GET',
          success: response => {
            wx.hideLoading(); // 登录成功，隐藏加载提示

            console.log('后端code登录请求', response.data);
            if (response.data.data && response.data.data.token && response.data.data.userId  && response.data.data.tokenExpireTime) {
              // 存储 Token 和 userId
              this.globalData.userToken = response.data.data.token;
              this.globalData.userId = response.data.data.userId;
              this.globalData.tokenExpireTime = response.data.data.tokenExpireTime;
              wx.setStorageSync('userToken', response.data.data.token);
              wx.setStorageSync('userId', response.data.data.userId);
              wx.setStorageSync('tokenExpireTime', response.data.data.tokenExpireTime);
             console.log("userToken", this.globalData.userToken);

              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 2000
              });
            }
          },
          fail: err => {
            wx.hideLoading(); // 登录失败，隐藏加载提示
            wx.showToast({
              title: '登录失败，请重试',
              icon: 'none',
              duration: 2000
            });
            console.error('登录请求失败', err);
          }
        });
      },
      fail: err => {
        wx.hideLoading(); // wx.login 调用失败，隐藏加载提示
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none',
          duration: 2000
        });
        console.error('wx.login 调用失败', err);
      }
    });
  },
  checkTokenValidity() {
    const currentTime = Math.floor(Date.now() / 1000);
    const tokenExpireTime = this.globalData.tokenExpireTime;
    if (!this.globalData.userToken || currentTime >= tokenExpireTime) {
      // Token 已过期或不存在
      this.userLogin(); 
     

      // 重新登录
      // wx.showModal({
      //   title: '登录过期',
      //   content: '您的登录状态已过期，请重新登录。',
      //   showCancel: false,
      //   success: () => {
      //     this.userLogin(); // 重新登录
      //   }
      // });
      return false;
    }
    return true;
  }
});
